package com.yangjun.service.bussiness;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.common.ServerResponse;
import com.yangjun.common.enums.SubSiteType;
import com.yangjun.dao.mybatis.mapper.businessAnalysis.ChannelConversionMapper;
import com.yangjun.service.common.CommonService;
import com.yangjun.utils.DvDateUtils;

@Service
public class ChannelConversionService {
 	@Autowired
    private ChannelConversionMapper channelConversionMapper;
 	@Autowired
 	private CommonService commonService;
 	
	public List<Map<String,String>> getChannel1Data(String startDay,String endDay,String siteid,String utm_medium,String utm_source,String sort){
		List<Map<String,String>> resultList = Lists.newArrayList();
		String[] siteidArr = null;
		String[] utmMediumArr = null;
		List<Map<String,Object>> dataList = null;
		Map<String,String> itemMap = null;
		
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		if(utmMediumArr!=null){
			//web端数据有一级渠道
			dataList = channelConversionMapper.queryWebUtmMediumData(startDay,endDay,siteidArr,utmMediumArr,utm_source.split(","),utm_source.contains("二级空渠道"),sort);
		}else{
			//APP数据没有一级渠道
			dataList = channelConversionMapper.queryAppUtmMediumData(startDay,endDay,siteidArr,utm_source.split(","),sort);
		}
		if(dataList.size()>0){
		for(Map<String,Object> data : dataList){
			itemMap = Maps.newHashMap();
			for(Map.Entry<String,Object> entry : data.entrySet()){
				itemMap.put(entry.getKey().toLowerCase(), entry.getValue()==null?"0":entry.getValue().toString());
			}
			resultList.add(itemMap);
		}
	}
	return resultList;
 	}
	public List<Map<String,String>> getChannel2Data(String startDay,String endDay,String siteid,String utm_medium,String utm_source,String sort){
		List<Map<String,String>> resultList = Lists.newArrayList();
		Boolean isMobile = false;
		String[] siteidArr = null;
		String[] utmMediumArr = null;
		Map<String,String> itemMap = null;
		
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(Arrays.asList(siteidArr).contains("14")||Arrays.asList(siteidArr).contains("15")){
			isMobile = true;
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		List<Map<String,Object>> dataList  = channelConversionMapper.queryChannel2Data(startDay,endDay,siteidArr,utmMediumArr,utm_source.split(","),utm_source.contains("二级空渠道"),sort,isMobile);
		
		if(dataList.size()>0){
			for(Map<String,Object> data : dataList){
				itemMap = Maps.newHashMap();
				if(data.get("UTM_SOURCE")==null){
					itemMap.put("utm_source", "二级空渠道");
				}
				for(Map.Entry<String,Object> entry : data.entrySet()){
					itemMap.put(entry.getKey().toLowerCase(), entry.getValue()==null?"0":entry.getValue().toString());
				}
				resultList.add(itemMap);
			}
		}
		
		return resultList;
	}
	public List<String> queryUtmSourceDimension(String siteid,String utm_medium){
		List<String> resultList = Lists.newArrayList();
		List<Map<String,Object>> dataList = null;
		List<String> siteidList = null;
		String[] utmMediumArr = null;
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		if(StringUtils.isNotEmpty(siteid)){
			String[] siteidArr = siteid.split(",");
			siteidList = Arrays.asList();
			if(!siteidList.contains("14")||siteidList.contains("15")){
				dataList = channelConversionMapper.queryUtmSourceDimension(siteidArr,utmMediumArr);
			}else{
				dataList = channelConversionMapper.queryUtmSourceDimension(siteidArr,null);
			}
		}
		if(dataList.size()>0){
			for(Map<String,Object> data : dataList){
				if(data!=null){
					if(data.get("UTM_SOURCE")!=null){
						resultList.add(data.get("UTM_SOURCE").toString());
					}
				}else{
					resultList.add("二级空渠道");
				}
			}
		}
		Collections.sort(resultList);
		return resultList;
	}
	
	
	public List<String> queryUtmMediumDimension(String siteid,String userid){
		List<String> siteidList = null;
		if(StringUtils.isNotEmpty(siteid)){
			siteidList = Arrays.asList(siteid.split(","));
			if(siteidList.contains(String.valueOf(SubSiteType.weixin.getSiteId()))){
				return commonService.getDim(userid,"channelConversion",Arrays.asList(DVConstants.VMALL_UTM_MEDIUM));
			}else if(siteidList.contains(String.valueOf(SubSiteType.PC.getSiteId()))||siteidList.contains(String.valueOf(SubSiteType.WAP.getSiteId()))){
				return commonService.getDim(userid,"channelConversion",Arrays.asList(DVConstants.PC_WAP_UTM_MEDIUM));
			}
		}
		return null;
	}
	
	
	public Object getSite(String userid){
		List<String> siteList = commonService.getDim(userid,"channelConversion",Arrays.asList(DVConstants.ZI_JIAN_SITE));
		return ServerResponse.createBySuccess(SubSiteType.getSubSiteTypeMap(siteList));
	}
	
	public List<Map<String,String>> queryLastMonthData(String beginDay,String endDay,String siteid,String utm_medium,String utm_source,String sort){
		List<Map<String,String>> resultList = Lists.newArrayList();
		Date lastMonthDate = DvDateUtils.getOffsetDay(new Date(), -31);
		String[] siteidArr = null;
		String[] utmMediumArr = null;
		Map<String,String> itemMap = null;
		Boolean isMobile = false;
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(Arrays.asList(siteidArr).contains("14")||Arrays.asList(siteidArr).contains("15")){
			isMobile = true;
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		List<Map<String,Object>> dataList  = channelConversionMapper.queryMonthData(beginDay,endDay,siteidArr,utmMediumArr,utm_source.split(","),utm_source.contains("二级空渠道"),sort,isMobile);
		if(dataList.size()>0){
			for(Map<String,Object> data : dataList){
				if(DvDateUtils.StrToDate(data.get("DATE_DAY").toString(),"yyyy-MM-dd").after(lastMonthDate)){
					itemMap = Maps.newHashMap();
					for(Map.Entry<String,Object> entry : data.entrySet()){
						itemMap.put(entry.getKey().toLowerCase(), entry.getValue()==null?"0":entry.getValue().toString());
					}
					resultList.add(itemMap);
				}
			}
		}
		return resultList;
	}
	public List<Map<String,String>> queryLastYearData(String startOfMonth,String endOfMonth,String siteid,String utm_medium,String utm_source,String sort){
		List<Map<String,String>> resultList = Lists.newArrayList();
		Date lastYearDate = DvDateUtils.getOffsetMonth(new Date(), -12);
		String[] siteidArr = null;
		String[] utmMediumArr = null;
		Map<String,String> itemMap = null;
		Boolean isMobile = false;
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(Arrays.asList(siteidArr).contains("14")||Arrays.asList(siteidArr).contains("15")){
			isMobile = true;
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		List<Map<String,Object>> dataList  = channelConversionMapper.queryYearData(startOfMonth,endOfMonth,siteidArr,utmMediumArr,utm_source.split(","),utm_source.contains("二级空渠道"),sort,isMobile);
		
		if(dataList.size()>0){
			for(Map<String,Object> data : dataList){
				if(DvDateUtils.StrToDate(data.get("DATE_DAY").toString(),"yyyy-MM").after(lastYearDate)){
					itemMap = Maps.newHashMap();
					//需求不明确，后面全部改为用实体
					itemMap.put("date_day",data.get("DATE_DAY")==null?"0":data.get("DATE_DAY").toString());
					itemMap.put("register",data.get("REGISTER")==null?"0":data.get("REGISTER").toString());
					itemMap.put("new_netamt_proportion",data.get("NEW_NETAMT_PROPORTION")==null?"0":data.get("NEW_NETAMT_PROPORTION").toString());
					itemMap.put("netamt",data.get("NETAMT")==null?"0":data.get("NETAMT").toString());
					itemMap.put("new_netamt",data.get("NEW_NETAMT")==null?"0":data.get("NEW_NETAMT").toString());
					itemMap.put("visitors",data.get("VISITORS")==null?"0":data.get("VISITORS").toString());
					itemMap.put("new_visitors",data.get("NEW_VISITORS")==null?"0":data.get("NEW_VISITORS").toString());
					itemMap.put("orders",data.get("ORDERS")==null?"0":data.get("ORDERS").toString());
					itemMap.put("new_visitors_proportion",data.get("NEW_VISITORS_PROPORTION")==null?"0":data.get("NEW_VISITORS_PROPORTION").toString());
					itemMap.put("order_conversion",data.get("ORDER_CONVERSION")==null?"0":data.get("ORDER_CONVERSION").toString());
					itemMap.put("new_orders",data.get("NEW_ORDERS")==null?"0":data.get("NEW_ORDERS").toString());
					itemMap.put("new_order_proportion",data.get("NEW_ORDER_PROPORTION")==null?"0":data.get("NEW_ORDER_PROPORTION").toString());	
					resultList.add(itemMap);
				}
				
			}
		}
		return resultList;
	}
	public Map<String,Object> queryLastTwoMonthData(String siteid,String utm_medium,String utm_source){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");

		Calendar calendar = Calendar.getInstance();
		String[] legendArr = null;
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH,1);
		String startDayOfTheMonth = format.format(calendar.getTime());
		String thisMonth = monthFormat.format(calendar.getTime());
		calendar.add(Calendar.MONTH,1);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String endDayOfTheMonth = format.format(calendar.getTime());
		calendar.add(Calendar.MONTH,-1);
		String endDayOfLastMonth = format.format(calendar.getTime());
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DATE, 1);
		calendar.add(Calendar.DAY_OF_MONTH, -1); 
		String lastMonth = monthFormat.format(calendar.getTime());
		calendar.set(Calendar.DATE, 1);
		String startDayOfLastMonth = format.format(calendar.getTime());

		String[] siteidArr = null;
		String[] utmMediumArr = null;
		String[] utmSourceArr = null;
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		if(StringUtils.isNotEmpty(utm_source)){
			utmSourceArr = utm_source.split(",");
		}
		Map<String,Object> theMonthItemMap = getCompareData(channelConversionMapper.queryMonthData(startDayOfTheMonth,endDayOfTheMonth,siteidArr,utmMediumArr,utmSourceArr,utm_source.contains("二级空渠道"),null,null),DVConstants.MONTH_DAY,null);
		Map<String,Object> lastMonthItemMap = getCompareData(channelConversionMapper.queryMonthData(startDayOfLastMonth,endDayOfLastMonth,siteidArr,utmMediumArr,utmSourceArr,utm_source.contains("二级空渠道"),null,null),DVConstants.MONTH_DAY,null);
		legendArr = new String[]{thisMonth,lastMonth};
		return getResultList(theMonthItemMap,lastMonthItemMap,new String[]{"visitors","order_conversion","new_visitors_proportion","new_order_proportion"},legendArr,DVConstants.MONTH_DAY);
	}
	
	public Map<String,Object> queryLastTwoYearData(String siteid,String utm_medium,String utm_source){
		SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); 
		SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");

		Calendar yearCalendar = Calendar.getInstance();
		yearCalendar.setTime(new Date());
		yearCalendar.set(Calendar.MONTH, 0);
		yearCalendar.set(Calendar.DAY_OF_MONTH, 1);

		String thisYearJanuary = dayFormat.format(yearCalendar.getTime());

		yearCalendar.add(Calendar.MONTH, 12);
		yearCalendar.add(Calendar.DAY_OF_MONTH, -1);
		String thisYearDecember = dayFormat.format(yearCalendar.getTime());
		String thisYear = yearFormat.format(yearCalendar.getTime());
		
		yearCalendar.add(Calendar.YEAR, -1);
		String lastYearDecember =dayFormat.format(yearCalendar.getTime());
		yearCalendar.add(Calendar.MONTH, -12);
		yearCalendar.add(Calendar.DAY_OF_MONTH, 1);
		String lastYearJanuary =dayFormat.format(yearCalendar.getTime());
		String lastYear = yearFormat.format(yearCalendar.getTime());


		String[] siteidArr = null;
		String[] utmMediumArr = null;
		String[] utmSourceArr = null;
		if(StringUtils.isNotEmpty(siteid)){
			siteidArr = siteid.split(",");
		}
		if(StringUtils.isNotEmpty(utm_medium)){
			utmMediumArr = utm_medium.split(",");
		}
		if(StringUtils.isNotEmpty(utm_source)){
			utmSourceArr = utm_source.split(",");
		}
		Map<String,Object> theYeartemMap = getCompareData(channelConversionMapper.queryYearData(thisYearJanuary,thisYearDecember,siteidArr,utmMediumArr,utmSourceArr,utm_source.contains("二级空渠道"),null,null),DVConstants.MONTH,"year");
		Map<String,Object> lastYearItemMap = getCompareData(channelConversionMapper.queryYearData(lastYearJanuary,lastYearDecember,siteidArr,utmMediumArr,utmSourceArr,utm_source.contains("二级空渠道"),null,null),DVConstants.MONTH,"year");
		String[] legendArr = new String[]{thisYear,lastYear};
		return getResultList(theYeartemMap,lastYearItemMap,new String[]{"visitors","order_conversion","new_visitors_proportion","new_order_proportion"},legendArr,DVConstants.MONTH_ARR_NAME);
	}
	
	private Map<String,Object> getResultList(Map<String,Object> theMonthItemMap,Map<String,Object> lastMonthItemMap,String[] dimensionArr,String[] legendArr,String[] xAxisArr){
		Map<String,Object> reusltMap = Maps.newHashMap();
		Map<String,Object> itemMap = null;
		for(String dimension : dimensionArr){
			itemMap = Maps.newHashMap();
			itemMap.put("currentData", theMonthItemMap==null?"":theMonthItemMap.get(dimension));
			itemMap.put("contrastData", lastMonthItemMap==null?"":lastMonthItemMap.get(dimension));
			itemMap.put("xAxis",xAxisArr);
			itemMap.put("legend",legendArr);
			reusltMap.put(dimension, itemMap);
		}
		System.out.println(reusltMap);
		return reusltMap;
	}
	private Map<String,Object> getCompareData(List<Map<String,Object>> dataList,String[] xAxisArr,String flag){
		SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat monthFormat = new SimpleDateFormat("MM"); 
		Map<String,Object> itemMap = Maps.newHashMap();;
		String[] orderConversionArr = new String[xAxisArr.length]; 
		String[] visitorsArr = new String[xAxisArr.length];
		String[] newVisitorsProportionArr = new String[xAxisArr.length];
		String[] newOrderProportionArr = new String[xAxisArr.length];
		try {
			if(dataList.size()>0){
				for(Map<String,Object> data : dataList){
					String date_day = data.get("DATE_DAY").toString();
					if(StringUtils.isNotEmpty(flag)){
						date_day = monthFormat.format(dayFormat.parse(date_day));
					}else{
						date_day = getDDofDate(date_day);
					}
					for(int i=0;i<xAxisArr.length;i++){
						if(date_day.equals(xAxisArr[i])){
							orderConversionArr[i] = data.get("ORDER_CONVERSION").toString();
							visitorsArr[i] = data.get("VISITORS").toString();
							newVisitorsProportionArr[i] = data.get("NEW_VISITORS_PROPORTION").toString();
							newOrderProportionArr[i] = data.get("NEW_ORDER_PROPORTION").toString();
						}
					}
				}
			}
			for(int i=0;i<xAxisArr.length;i++){
					if(StringUtils.isBlank(orderConversionArr[i])){
						orderConversionArr[i]="0";
					}
					if(StringUtils.isBlank(visitorsArr[i])){
						visitorsArr[i]="0";
					}
					if(StringUtils.isBlank(newVisitorsProportionArr[i])){
						newVisitorsProportionArr[i]="0";
					}
					if(StringUtils.isBlank(newOrderProportionArr[i])){
						newOrderProportionArr[i]="0";
					}
			}
			itemMap.put("order_conversion", orderConversionArr);
			itemMap.put("visitors", visitorsArr);
			itemMap.put("new_visitors_proportion", newVisitorsProportionArr);
			itemMap.put("new_order_proportion", newOrderProportionArr);
		}catch (Exception e){
			e.printStackTrace();
		}
		return itemMap;
	}
	private String getDDofDate(String date){
		String resultStr = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		SimpleDateFormat transFormat = new SimpleDateFormat("dd"); 
		try {
			resultStr = transFormat.format(format.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return resultStr;
	}
	
}
